package com.mocoder.chatdemo.view;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.HashMap;

import javax.imageio.ImageIO;

import com.mocoder.chatdemo.model.CallbackFunc;
import com.mocoder.chatdemo.protocol.ProtocolHelper;
import javafx.application.Platform;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Orientation;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.SplitPane;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

/**
 * Created by yangshuai on 2018/3/9.
 */
public class UIHelper {

    private static double chatLogPosition = 0.7459349593495935;

    private static final HashMap<String, Tab> chatTabs = new HashMap<>();

    public static void createChatRoomTab(TabPane pane) {
        addChatRecord(pane, null, null, true, true);
    }

    public static void addChatRecord(TabPane pane, InetAddress msgFrom, String msg, boolean isRoom) {
        addChatRecord(pane, msgFrom, msg, isRoom, false);
    }

    public static void createChatFriendTab(TabPane pane, InetAddress friendAddr) {
        addChatRecord(pane, friendAddr, null, false, true);
    }

    private static void addChatRecord(TabPane pane, InetAddress msgFrom, String msg, boolean isRoom,
                                      boolean popTab) {
        String id = isRoom ? "255.255.255.255" : msgFrom.getHostAddress();
        Tab tab = chatTabs.get(id);
        if (tab == null) {
            tab = newTab(id, msgFrom, isRoom);
            pane.getTabs().add(tab);
            chatTabs.put(id, tab);
        }
        if (popTab) {
            pane.getSelectionModel().select(tab);
        }
        if (msg != null && !msg.isEmpty()) {
            SplitPane pane1 = (SplitPane)tab.getContent();
            TextArea chatLog = (TextArea)pane1.getItems().get(0);
            String name = ProtocolHelper.getUserName(msgFrom);
            chatLog.appendText("\n" + name + " : " + msg);
        }
    }

    private static Tab newTab(String id, InetAddress msgFrom, boolean isRoom) {
        Tab tab = new Tab(isRoom ? "本地局域网" : ProtocolHelper.getUserName(msgFrom));
        tab.setClosable(true);
        tab.setOnCloseRequest(new EventHandler<Event>() {
            @Override
            public void handle(Event event) {
                chatTabs.remove(id);
            }
        });
        SplitPane splitPane = new SplitPane();
        TextArea chatLog = new TextArea();
        chatLog.setEditable(false);
        chatLog.setWrapText(true);
        TextArea chatInput = new TextArea();
        chatInput.setEditable(true);
        chatInput.setWrapText(true);
        chatInput.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent keyEvent) {
                TextArea input = (TextArea)keyEvent.getSource();
                if (!keyEvent.getCode().equals(KeyCode.ENTER)) {
                    return;
                } else if (keyEvent.isControlDown()) {
                    input.appendText("\n");
                    return;
                } else {
                    keyEvent.consume();
                    if (input.getText().isEmpty()) {
                        return;
                    }
                    ProtocolHelper.sendChatMsgData(isRoom, input.getText(), msgFrom, new CallbackFunc() {
                        @Override
                        public void success(Object resp) {
                            Platform.runLater(new Runnable() {
                                @Override
                                public void run() {
                                    if (!isRoom) {
                                        chatLog.appendText("\n[我] : " + input.getText());
                                    }
                                    input.setText("");
                                }
                            });
                        }
                    });
                }
            }
        });
        splitPane.setDividerPositions(chatLogPosition);
        splitPane.setOrientation(Orientation.VERTICAL);
        splitPane.getItems().add(chatLog);
        splitPane.getItems().add(chatInput);
        tab.setContent(splitPane);
        return tab;
    }

    public static void alert(String msg) {
        Alert alert = new Alert(AlertType.INFORMATION);
        alert.setContentText(msg);
        alert.show();
    }

    public static byte[] zoomPic(File imageFile, int width, int height) throws IOException {
        Image image = ImageIO.read(imageFile);
        image = image.getScaledInstance(40, 40, Image.SCALE_SMOOTH);
        BufferedImage newImg = new BufferedImage(40, 40, BufferedImage.TYPE_3BYTE_BGR);
        newImg.getGraphics().drawImage(image, 0, 0, null);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(5000);
        ImageIO.write(newImg, "png", outputStream);
        return outputStream.toByteArray();
    }
}
